#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <signal.h>

static const int server_port = 4433;
BIO * bio_err;
int server_running = 1;

int create_socket(void)
{
    int s;
    int optval = 1;
    struct sockaddr_in addr;

    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        perror("Unable to create socket");
        exit(EXIT_FAILURE);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(server_port);
    addr.sin_addr.s_addr = INADDR_ANY;

    /* Reuse the address; good for quick restarts */
    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))
            < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }

    if (bind(s, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        perror("Unable to bind");
        exit(EXIT_FAILURE);
    }

    if (listen(s, 1) < 0) {
        perror("Unable to listen");
        exit(EXIT_FAILURE);
    }

    return s;
}

SSL_CTX* create_context(void)
{
    SSL_CTX *ctx;
    ctx = SSL_CTX_new(TLS_server_method());
    if (ctx == NULL) {
        perror("Unable to create SSL context");
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }

    return ctx;
}

void configure_server_context(SSL_CTX *ctx)
{
    /* Set the key and cert */
    if (SSL_CTX_use_certificate_chain_file(ctx, "cert.pem") <= 0) {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
       if (!SSL_CTX_check_private_key(ctx))
    {
        printf("Private key does not match the certificate public key\n");
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
}

void usage()
{
    printf("Usage: sslecho \n");
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv)
{
    SSL_CTX *ssl_ctx = NULL;
    SSL *ssl = NULL;
    BIO *sbio,*b;

    int server_skt = -1;
    int client_skt = -1;

    /* used by getline relying on realloc, can't be statically allocated */
    char *txbuf = NULL;
    size_t txcap = 0;

    char rxbuf[128];
    size_t rxcap = sizeof(rxbuf);
    int len;

    struct sockaddr_in addr;
    unsigned int addr_len = sizeof(addr);

    /* ignore SIGPIPE so that server can continue running when client pipe closes abruptly */
    signal(SIGPIPE, SIG_IGN);

    printf("\nsslecho : Simple Echo Server (OpenSSL 3.2.0-dev) : %s : %s\n\n", __DATE__,
            __TIME__);

    if (argc > 1) {
        usage();
    }

    ssl_ctx = create_context();


    printf("We are the server on port: %d\n\n", server_port);

    /* Configure server context with appropriate key files */
    configure_server_context(ssl_ctx);

    /* Create server socket; will bind with server port and listen */
    server_skt = create_socket();
    /*
     * Loop to accept clients.
     * Need to implement timeouts on TCP & SSL connect/read functions
     * before we can catch a CTRL-C and kill the server.
     */
    while (server_running) {
        /* Wait for TCP connection from client */
        client_skt = accept(server_skt, (struct sockaddr*) &addr,
                &addr_len);
        if (client_skt < 0) {
            perror("Unable to accept");
            exit(EXIT_FAILURE);
        }


        printf("Client TCP connection accepted\n");

        /* Create server SSL structure using newly accepted client socket */
        ssl = SSL_new(ssl_ctx);
        SSL_set_fd(ssl, client_skt);

        sbio = BIO_new_socket(client_skt,BIO_NOCLOSE);
        b = BIO_new(BIO_s_mem());
        /* Wait for SSL connection from the client */
        if (SSL_accept(ssl) <= 0) {
            ERR_print_errors_fp(stderr);
            server_running = 0;
        } else {

            /* Check for Client authentication error */
            if (SSL_get_verify_result(ssl) != X509_V_OK) {
                printf("SSL Client Authentication error\n");
                exit(EXIT_FAILURE);
            }
            printf("Client SSL connection accepted\n\n");

            bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
            unsigned char buf[128];
            /* Echo loop */
            while (1) {
                /* Get message from client; will fail if client closes connection */
                BIO_printf(bio_err,"aaaaaa");
                SSL_set_bio(ssl,sbio,sbio);
                int size = BIO_read(sbio,buf,128);
                BIO_printf(bio_err,"bbbbbb");
                if(size <= 0)
                {
                    if(size == 0)
                        BIO_printf(bio_err,"close!\n");
                    else
                        BIO_printf(bio_err,"SSL return %d!\n",size);
                    break;
                }
                if(size > 0)
                {
                    BIO_printf(bio_err,"size:%d \n",size);

                    for(int i = 0; i < size; i++)
                    {
                        BIO_printf(bio_err,"%02x ",buf[i]);
                        if((i + 1) % 8 == 0)
                            BIO_printf(bio_err,"\n");
                    }
                    BIO_printf(bio_err,"\n");
                }
                // const EVP_CIPHER* cipher = SSL_get_cipher(ssl);
                // BIO_printf(bio_err,"%s \n",cipher);
                
                SSL_set_bio(ssl,b,b);
                size = BIO_write(b,buf,128);
                
                if ((len = SSL_read(ssl, buf, sizeof(buf))) <= 0) {
                    if (len == 0) {
                        printf("Client closed connection\n");
                    } else {
                        printf("SSL_read returned %d\n", len);
                    }
                    ERR_print_errors_fp(stderr);
                    break;
                }else
                    /* Show received message */
                {
                    printf("Received: %s", buf);
                    /* Echo it back */
                    if (SSL_write(ssl, buf, len) <= 0) {
                        ERR_print_errors_fp(stderr);
                    }
                }
            }
        }
        if (server_running) {
            /* Cleanup for next client */
            BIO_printf(bio_err,"enter..");
            BIO_free(sbio);
            BIO_free(b);
            SSL_shutdown(ssl);
            SSL_free(ssl);
            close(client_skt);
        }
    }
    printf("Server exiting...\n");
    /* Close up */
    if (ssl != NULL) {
        SSL_shutdown(ssl);
        SSL_free(ssl);
    }
    SSL_CTX_free(ssl_ctx);

    if (server_skt != -1)
        close(server_skt);

    if (txbuf != NULL && txcap > 0)
        free(txbuf);

    printf("sslecho exiting\n");

    return EXIT_SUCCESS;
}
